<?php
class Model_Blocks extends Model{

    protected static $_instance =  null;
	/**
     * @return Model_Blocks
     */
	static public function getInstance(){
        if(is_null(self::$_instance))	
           self::$_instance = new self('blocks');     
        return self::$_instance;   
    }
    
    /**
     * Get block list for page
     * Enter description here ...
     * @param integer $page
     * @param array $fields
     * @return array  - block list sorted by place code
     */
    public function getPageBlocks($page , array $fields){
        
        $bMapping = Db_Object_Config::getInstance('blockmapping');
        
        $sql = $this->_db->select()
                         ->from(array('t'=>$this->table()),$fields)
                         ->join(
                             array('map'=>$bMapping->table()),
                             't.id = map.block_id',
                             array('place')
                        )
                        ->where('t.page_id = ' . intval($page))
                        ->order('map.order_no ASC');

        $data = $this->_db->fetchAll($sql);
        if(empty($data))
            return array();
            
        $result = array();    
        foreach ($data as $k=>$v){          
            $key = $v['place'];
            
            if(!isset($result[$v['place']]))
                $result[$key] = array();
           
             unset($v['place']);    
                
            $result[$key] = $v;  
        }         

        return $data;
    }
   
    
    /**
     * Set block mapping for page
     * @param integer $pageId
     * @param array $map    like  array(
     * 		'code'=>array('blockid1','blockid2'),...
     * 		'code3'=>array('blockid4','blockid7)
     * )
     */
    public function setMapping($pageId , array $map){
        
        $bMapping = Model_Blockmapping::getInstance();
        $bMapping->clearMap($pageId);
        
        if(empty($map))
            return true;
            
        foreach ($map as $code => $items)
            $bMapping->addBlocks($pageId, $code, $items);
         
       return true;     
    }
}